<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Json_formatter {
	
	private $CI;
	private $rs;
	private $id;
	private $fields = array();
		
	function __construct()
	{
		$this->CI =& get_instance();
		$this->CI->load->database();
	}
	
	/**
	 * initialize
	 * 
	 * Initialize configurable global variables
	 * 
	 * @access public
	 * @param object
	 * @param string
	 * @return void
	 */
	function initialize($rs, $id)
	{
		$this->rs = $rs;
		$this->id = $id;
	}
	
	/**
	 * _run
	 * 
	 * Create json string
	 * 
	 * @access private
	 * @param object
	 * @param string
	 * @return string
	 */	
	function _run($rs, $id) 
	{
		$this->initialize($rs, $id);
		$this->pop_fields();
		return $this->_json_encode();
	}
	
	/**
	 * pop_fields
	 * 
	 * Map result set field names
	 * 
	 * @access public
	 * @param void
	 * @return void
	 */
	function pop_fields()
	{
		$this->fields = $this->rs->field_data();
	}
	
	/**
	 * _json_encode
	 * 
	 * Create a json string suitable for jqGrid
	 * 
	 * @access private
	 * @param void
	 * @return string
	 */
	function _json_encode()
	{
		$json = '[';
		
		$result = $this->rs->result();
		
		foreach ($result as $row)
		{
			$id = $this->id;
			
			// Set primary key of row
			$json .= '{"id": "'. $row->$id .'",';
			
			$json .= '"cell":[';
			
			// Per column traversal
			// Maps field values
			foreach ($this->fields as $cols)
			{
				$field = $cols->name;
				
				// Clean field value
				$json .= '"'. $this->parse($row->$field) .'",';
			}
			
			// Remove last comma from row
			$json = substr($json, 0, -1);
			
			$json .= ']},';
		}
		
		// Remove last comma from whole json
		$json = substr($json, 0, -1);
		
		$json .= ']';
		
		return $json;
	}

	/**
	 * parse
	 * 
	 * Parse string to a friendlier format
	 * 
	 * @access public
	 * @param string
	 * @return string
	 */
	function parse($text) 
	{
		// In case we encounter new line characters
		$parsed = str_replace(chr(10), ' ', $text);
		
		// Escape quoted strings
		$parsed = str_replace('"', '\"', $parsed);
		
		// Change return characters
		return str_replace(chr(13), ' ', $parsed);
	}
}

/* End of file Json_formatter.php */
/* Location: ./application/libraries/Json_formatter.php */
